<template>
  <div class="queue-wrap">
    <continer :showPage="showPage" :isNoTabs="true">
      <template slot="search">
        <QuickSearch :advForm="quickSearchForm" @QuickSearch="queryQueueList"></QuickSearch>
      </template>
      <template slot="oprate">
        <el-button type="primary" size="mini" @click="queryQueueList">查询</el-button>
        <el-button size="mini" @click="addBtnFun" v-functions="['skillGroup_management_insert']">新增</el-button>
      </template>
      <template slot="content">
        <instiutionTable ref="tableRef"
                         class="instiutionTable"
                         :pages="queueTablePages"
                         :instiutionTableData="queueTableData"
                         :instiutionTableHeader="queueTableHeader"
                         :batchOperate="batchOperate"
                         @batchClick="batchClick"
                         @sizeChange="sizeChange"
                         @currentChange="currentChangeFun">
        </instiutionTable>
      </template>
      <template slot="page">
        <addOrEditQueue :agentList="agentListArr" :titleArr="titleArr" @saveFun="saveFun" @cancelFun="back" ref="addOrEditQueueRef" @pageBack="pageBack"></addOrEditQueue>
      </template>
    </continer>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Ref } from 'vue-property-decorator'
import { deepClone } from '@/utils/common'
import { checkPermission } from '@/utils/directive'
import { CommonModule } from '@/store/modules/common'
import QuickSearch from '@/common/views/advancedSearch/QuickSearch.vue'
import instiutionTable from '@/common/views/institutionTable/institutionTable.vue'
import continer from '@/common/views/configCommon/ui-modules/handle-wrapper.vue'
import breadcrumb from '@/components/breadcrumb/breadcrumb.vue'
import addOrEditQueue from '@/views/config/queue/addOrEditQueue.vue'
import { organizationConfigModule } from '@/store/modules/config/organizationConfig/index'
@Component({
  name: 'queue',
  components: {
    QuickSearch,
    instiutionTable,
    breadcrumb,
    addOrEditQueue,
    continer
  }
})
export default class Queue extends Vue {
  [x: string]: any
  private showPage: boolean = false
  @Ref() private readonly addOrEditQueueRef !: addOrEditQueue
  @Ref() private readonly tableRef !: instiutionTable
  private quickSearchForm = {
    form: {
      name: ''
    },
    advSearchOptions: [ // 高级搜索数据
      { label: '技能组名称', inputType: 'input', placeholder: '请输入技能组名称', name: 'name' }
    ]
  }

  private batchOperate = [ // 批量操作设置
    { name: '批量删除', action: 'batchDelAgentFun', _id: 'skillGroup_management_batch_delete' }
  ]

  private titleArr: any[] = []

  private queueTablePages = { // 表格分页
    current: 1,
    pageSize: 10,
    total: 0
  }

  private queueTableData = []

  private queueTableHeader: any[] = [ // 表头
    { type: 'select' },
    { label: '技能组名称', prop: 'name' },
    { label: '技能组ID', prop: '_id' },
    { label: '更新人', prop: 'createName' },
    { label: '最后更新时间', prop: 'updateTime', isSort: true }
  ]

  get agentListArr () {
    const agents = deepClone(CommonModule.publicCache.userListObj)
    const agentsArr: any = []
    for (const i in agents) {
      agentsArr.push({ key: agents[i]._id, label: agents[i].name })
    }
    return agentsArr
  }

  private pageBack () {
    this.showPage = false
  }

  private batchClick (action, selectList) {
    this[action](selectList)
  }

  private addBtnFun () { // 新增按钮点击事件
    this.showPage = true
    this.titleArr = ['技能组管理', '添加技能组']
    this.$nextTick(() => {
      this.addOrEditQueueRef.setQueueData()
    })
  }

  private sizeChange (size: number) {
    this.queueTablePages.pageSize = size
    this.queryQueueList()
  }

  private currentChangeFun (page: number) { // 翻页
    this.queueTablePages.current = page
    this.queryQueueList()
  }

  private handleEdit (obj: any) { // 修改技能组
    this.showPage = true
    this.titleArr = ['技能组管理', '编辑技能组']
    this.$nextTick(() => {
      this.addOrEditQueueRef.setQueueData(obj)
    })
  }

  private handleDel (obj: any) { // 删除技能组
    this.$confirm('确定要删除该技能组吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const actionData = { url: '/base/action/skillGroup/delete', method: 'POST', data: { _id: obj._id } }
      organizationConfigModule.organizationCommonAction(actionData).then(res => {
        this.$message.success('删除技能组成功')
        this.$deleteCache('queueList', '_id', obj._id, true)
        this.queryQueueList()
      })
    })
  }

  private batchDelAgentFun (selectedArr: any) { // 批量删除
    this.$confirm('确定要批量删除技能组吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      let sendData = {}
      if (typeof selectedArr === 'object') { // 单个操作，传ids
        sendData = { ids: selectedArr || [] }
      } else { // 全选传查询条件
        sendData = { condition: { page: this.queueTablePages.current, limit: this.queueTablePages.pageSize, ...this.quickSearchForm.form } }
      }
      const actionData = { url: '/base/action/skillGroup/batch/delete', method: 'POST', data: sendData }
      organizationConfigModule.organizationCommonAction(actionData).then(res => {
        if (res) {
          this.$message.success('批量删除技能组成功')
          this.tableRef.cancelSelectFun() // 关闭批量操作栏
          this.queryQueueList()
        }
      })
    })
  }

  private saveFun (type) {
    this.queryQueueList(type)
    this.back()
  }

  private queryQueueList (addSuccess?: any) {
    if (addSuccess) { // 新增回到第一页
      this.queueTablePages.current = 1
    }
    const sendData = { page: this.queueTablePages.current, limit: this.queueTablePages.pageSize, ...this.quickSearchForm.form }
    const actionData = { url: '/base/action/skillGroup/query', method: 'POST', data: { ...sendData } }
    organizationConfigModule.organizationCommonAction(actionData).then(res => {
      if (res.list) {
        const list = res.list || []
        if (list.length === 0) {
          const page = Math.ceil(res.count / this.queueTablePages.pageSize)
          if (!res.count) { // 第一页且count为0是不再发请求（!res.count，以防后端没有返回count,直接死循环）
            this.queueTablePages.current = 1
          } else { // 删除到最后一个回到上一页
            this.queueTablePages.current = page
            this.queryQueueList()
            return false
          }
        }
        list.forEach(item => {
          const agentObj = deepClone(CommonModule.publicCache.userListObj)[item.updateUser]
          item.createName = agentObj ? agentObj.name : '--'
        })
        this.queueTableData = res.list
        this.queueTablePages.total = res.count
      }
    })
  }

  private back () {
    this.$nextTick(() => {
      this.addOrEditQueueRef.setQueueData()
      this.showPage = false
    })
  }

  private mounted () {
    this.queryQueueList()
  }

  private beforeMount () {
    const handlers: any[] = []
    if (checkPermission(null, { value: ['skillGroup_management_edit'] })) { // 编辑
      handlers.push({ name: '编辑', handleFn: (scope: any) => this.handleEdit(scope.row) })
    }
    if (checkPermission(null, { value: ['skillGroup_management_delete'] })) {
      handlers.push({ className: 'danger', name: '删除', handleFn: (scope: any) => this.handleDel(scope.row) })
    }
    this.batchOperate = this.batchOperate.filter(item => checkPermission(null, { value: [item._id] })) // 过滤批量操作的权限
    this.queueTableHeader.push({ label: '操作', width: 100, handlers })
  }
}
</script>

<style lang="stylus" scoped>
  .queue-wrap
     width 100%
     height 100%
     position relative
</style>
